package com.blog.blog.controller;

import com.blog.blog.config.SiteProperties;
import com.blog.blog.mapper.ArticleMapper;
import com.blog.blog.mapper.CategoryMapper;
import com.blog.blog.mapper.TagMapper;
import com.blog.blog.vo.ArticleListItemVO;
import com.blog.blog.vo.CategoryVO;
import com.blog.blog.vo.TagVO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.time.format.DateTimeFormatter;
import java.util.List;

@Tag(name = "SEO优化", description = "站点地图和搜索引擎优化相关接口")
@RestController
public class SitemapController {

    private final ArticleMapper articleMapper;
    private final CategoryMapper categoryMapper;
    private final TagMapper tagMapper;
    private final SiteProperties siteProperties;

    public SitemapController(ArticleMapper articleMapper, CategoryMapper categoryMapper, TagMapper tagMapper, SiteProperties siteProperties) {
        this.articleMapper = articleMapper;
        this.categoryMapper = categoryMapper;
        this.tagMapper = tagMapper;
        this.siteProperties = siteProperties;
    }

    @Operation(summary = "站点地图索引", description = "生成站点地图索引文件，包含所有子站点地图")
    @GetMapping(value = "/sitemap.xml", produces = MediaType.APPLICATION_XML_VALUE)
    public String sitemap() {
        // 输出索引：按 1000 条一分片
        long total = articleMapper.countPublished();
        int pageSize = 1000;
        int pages = (int) Math.max(1, (total + pageSize - 1) / pageSize);
        String base = siteProperties.getBaseUrl() != null ? siteProperties.getBaseUrl().replaceAll("/$", "") : "";
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
        
        // 文章分页sitemap
        for (int i = 1; i <= pages; i++) {
            sb.append("  <sitemap>\n");
            sb.append("    <loc>").append(base).append("/sitemap-articles-").append(i).append(".xml</loc>\n");
            sb.append("  </sitemap>\n");
        }
        
        // 静态页面sitemap
        sb.append("  <sitemap>\n");
        sb.append("    <loc>").append(base).append("/sitemap-pages.xml</loc>\n");
        sb.append("  </sitemap>\n");
        
        // 分类和标签sitemap
        sb.append("  <sitemap>\n");
        sb.append("    <loc>").append(base).append("/sitemap-categories.xml</loc>\n");
        sb.append("  </sitemap>\n");
        
        sb.append("</sitemapindex>");
        return sb.toString();
    }

    @Operation(summary = "文章站点地图", description = "生成指定页码的文章站点地图")
    @GetMapping(value = "/sitemap-articles-{page}.xml", produces = MediaType.APPLICATION_XML_VALUE)
    public String sitemapArticlesPage(@PathVariable("page") int pageNo) {
        int pageSize = 1000;
        int offset = (pageNo - 1) * pageSize;
        List<ArticleListItemVO> list = articleMapper.selectPublishedForSitemap(offset, pageSize);
        String base = siteProperties.getBaseUrl() != null ? siteProperties.getBaseUrl().replaceAll("/$", "") : "";
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
        // 首页
        if (pageNo == 1) {
            sb.append("  <url>\n");
            sb.append("    <loc>").append(base).append("/").append("</loc>\n");
            sb.append("    <changefreq>daily</changefreq>\n");
            sb.append("    <priority>1.0</priority>\n");
            sb.append("  </url>\n");
        }
        DateTimeFormatter fmt = DateTimeFormatter.ISO_DATE_TIME;
        for (ArticleListItemVO a : list) {
            sb.append("  <url>\n");
            sb.append("    <loc>").append(base).append("/article/").append(a.getId()).append("</loc>\n");
            if (a.getCreateTime() != null) {
                sb.append("    <lastmod>").append(fmt.format(a.getCreateTime())).append("</lastmod>\n");
            }
            sb.append("    <changefreq>weekly</changefreq>\n");
            sb.append("    <priority>0.8</priority>\n");
            sb.append("  </url>\n");
        }
        sb.append("</urlset>");
        return sb.toString();
    }

    @Operation(summary = "静态页面站点地图", description = "生成静态页面的站点地图")
    @GetMapping(value = "/sitemap-pages.xml", produces = MediaType.APPLICATION_XML_VALUE)
    public String sitemapPages() {
        String base = siteProperties.getBaseUrl() != null ? siteProperties.getBaseUrl().replaceAll("/$", "") : "";
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
        
        // 首页
        sb.append("  <url>\n");
        sb.append("    <loc>").append(base).append("/</loc>\n");
        sb.append("    <changefreq>daily</changefreq>\n");
        sb.append("    <priority>1.0</priority>\n");
        sb.append("  </url>\n");
        
        // 简历页面
        sb.append("  <url>\n");
        sb.append("    <loc>").append(base).append("/resume</loc>\n");
        sb.append("    <changefreq>weekly</changefreq>\n");
        sb.append("    <priority>0.9</priority>\n");
        sb.append("  </url>\n");
        
        // 归档页面
        sb.append("  <url>\n");
        sb.append("    <loc>").append(base).append("/archives</loc>\n");
        sb.append("    <changefreq>daily</changefreq>\n");
        sb.append("    <priority>0.8</priority>\n");
        sb.append("  </url>\n");
        
        // 分类索引页面
        sb.append("  <url>\n");
        sb.append("    <loc>").append(base).append("/categories</loc>\n");
        sb.append("    <changefreq>weekly</changefreq>\n");
        sb.append("    <priority>0.7</priority>\n");
        sb.append("  </url>\n");
        
        // 标签索引页面
        sb.append("  <url>\n");
        sb.append("    <loc>").append(base).append("/tags</loc>\n");
        sb.append("    <changefreq>weekly</changefreq>\n");
        sb.append("    <priority>0.7</priority>\n");
        sb.append("  </url>\n");
        
        sb.append("</urlset>");
        return sb.toString();
    }

    @Operation(summary = "分类和标签站点地图", description = "生成分类和标签页面的站点地图")
    @GetMapping(value = "/sitemap-categories.xml", produces = MediaType.APPLICATION_XML_VALUE)
    public String sitemapCategories() {
        String base = siteProperties.getBaseUrl() != null ? siteProperties.getBaseUrl().replaceAll("/$", "") : "";
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
        
        // 分类页面
        List<CategoryVO> categories = categoryMapper.listAll();
        for (CategoryVO category : categories) {
            sb.append("  <url>\n");
            sb.append("    <loc>").append(base).append("/category/").append(category.getId()).append("</loc>\n");
            sb.append("    <changefreq>weekly</changefreq>\n");
            sb.append("    <priority>0.6</priority>\n");
            sb.append("  </url>\n");
        }
        
        // 标签页面
        List<TagVO> tags = tagMapper.listAll();
        for (TagVO tag : tags) {
            sb.append("  <url>\n");
            sb.append("    <loc>").append(base).append("/tag/").append(tag.getId()).append("</loc>\n");
            sb.append("    <changefreq>weekly</changefreq>\n");
            sb.append("    <priority>0.5</priority>\n");
            sb.append("  </url>\n");
        }
        
        sb.append("</urlset>");
        return sb.toString();
    }

    @Operation(summary = "搜索引擎爬虫规则", description = "生成robots.txt文件，指导搜索引擎爬虫")
    @GetMapping(value = "/robots.txt", produces = MediaType.TEXT_PLAIN_VALUE)
    public String robots() {
        String base = siteProperties.getBaseUrl() != null ? siteProperties.getBaseUrl().replaceAll("/$", "") : "";
        StringBuilder sb = new StringBuilder();
        sb.append("User-agent: *\n");
        sb.append("Allow: /\n\n");
        sb.append("Sitemap: ").append(base).append("/sitemap.xml\n");
        return sb.toString();
    }
}


